package com.ruoyi.psi.quality.analysis.service;

import com.ruoyi.produce.process.defective.domain.Defective;
import com.ruoyi.produce.process.defective.mapper.DefectiveMapper;
import com.ruoyi.produce.process.worksheet.domain.ProduceWorkSheet;
import com.ruoyi.produce.process.worksheet.service.IProduceWorkSheetService;
import com.ruoyi.psi.quality.analysis.domain.QualityAnalysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class QualityAnalysisServiceImpl implements IQualityAnalysisService {
    @Autowired
    private DefectiveMapper defectiveMapper;
    @Autowired
    private IProduceWorkSheetService workSheetService;

    /**
     * 质检分析
     * @param defective
     * @return
     */
    @Override
    public List<QualityAnalysis> selectQualityAnalysis(Defective defective) {
        List<Defective> defectiveList = defectiveMapper.selectDefectiveList(defective);//根据时间查询质检数据
        Map<String, QualityAnalysis> workSheetMap = new HashMap<>(50); //用于存加工单编号，防止重复
        for (Defective item : defectiveList) {
            String workSheetId = item.getWorkSheetId();
            if (!workSheetMap.containsKey(workSheetId)) {
                ProduceWorkSheet workSheet = workSheetService.selectProduceWorkSheetById(workSheetId);
                Double defectiveNum = item.getDefectiveNum();
                Double total = item.getTotal();
                Double rightNum=total-defectiveNum;
                QualityAnalysis qualityAnalysis = new QualityAnalysis(
                        workSheetId,
                        workSheet.getProduceId(),
                        workSheet.getProduceName(),
                        defectiveNum,
                        total,
                        (rightNum / total)
                );
                workSheetMap.put(workSheetId, qualityAnalysis);
            } else {
                QualityAnalysis qualityAnalysis1 = workSheetMap.get(workSheetId);
                Double defectiveNum = qualityAnalysis1.getDefectiveNum() + item.getDefectiveNum(); // 累加不合格数
                Double total = qualityAnalysis1.getTotal() + item.getTotal(); // 累加总数
                Double rightNum=total-defectiveNum;
                qualityAnalysis1.setDefectiveNum(defectiveNum);
                qualityAnalysis1.setTotal(total);
                qualityAnalysis1.setQualifiedRate(rightNum / total);
                workSheetMap.replace(workSheetId, qualityAnalysis1);
            }
        }
        return new ArrayList<>(workSheetMap.values());
    }
}
